package fit.deni.pages;

import java.util.Collection;

import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.corelib.components.EventLink;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.hibernate.Hibernate;

import fit.deni.beans.Klub;
import fit.deni.beans.Zaposleni;
import fit.deni.hibernate.interfaces.KlubService;

public class Clubs {

	@Property
	private Collection<Klub> klubovi;
	@Property
	private Klub singleKlub;
	@Persist(PersistenceConstants.FLASH)
	@Property 
	private Klub noviKlub;
	
	@Property
	@SessionState
	private Zaposleni korisnik;
	private boolean korisnikExists;

	@Inject
	private KlubService klubService;
	
	@InjectPage
	private Club club;
	
	@Component
	private EventLink edit, delete;

	public void onDelete(String id) {
		try {
			klubService.deleteClub(klubService.getClubById(Integer.parseInt(id)));
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Here you should handle delete errors");
		}
	}
	
	public void onEdit(String id) {
		try {
			noviKlub = klubService.getClubById(Integer.parseInt(id));
			Hibernate.initialize(noviKlub.getTelefoni());
		} catch (Exception e) {
			e.printStackTrace();
			System.err.println("Here you should handle edit errors");
		}
	}
	
	public Object onSelect(String id) {
		Klub selected = klubService.getClubById(Integer.parseInt(id));
		club.setClub(selected);
		return club;
	}

	private Object onActivate() {
		if(!korisnikExists) return Login.class;
		klubovi = klubService.getAll();
		return null;
	}

	private Object onSuccess() {
		klubService.addClub(noviKlub);
		noviKlub = new Klub();
		return this;
	}
	
}
